package dbTools.util;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileUtil {
	
	public static String USER_COUNTRY_CHAR_SET;
	
	private String CHAR_SET="utf-8";
	
	// accessMode
	public static int F_READ = 1;
	public static int F_WRITE = 2;

	// createFlag:
	// Creates a new file. The function fails if the specified file already exists.
	public static final int CREATE_NEW = 1;
	// Creates a new file. If the file exists, the function overwrites the file and clears the existing attributes.
	public static final int CREATE_ALWAYS = 2;
	// Opens the file. The function fails if the file does not exist.
	public static final int OPEN_EXISTING = 3;
	// Opens the file, if it exists. If the file does not exist, the function creates the file as if dwCreationDisposition were CREATE_NEW.
	public static final int OPEN_ALWAYS = 4;
	// Opens the file. Once opened, the file is truncated so that its size is zero bytes. The function fails if the file does not exist.
	public static final int TRUNCATE_EXISTING = 5;

	public FileUtil()
	{ 
		
	}
	
	public FileUtil(String filePath,String fileName)
	{ 
		this.filePath = filePath.endsWith("\\")?filePath:filePath+"\\";
		this.fileName = this.filePath+fileName;
		this.CHAR_SET="UTF8";
	}
	
	public FileUtil(String filePath,String fileName, String CHAR_SET)
	{ 
		this.filePath = filePath.endsWith("\\")?filePath:filePath+"\\";
		this.fileName = this.filePath+fileName;
		this.CHAR_SET = CHAR_SET;
	}
	
	private File file;
	
	public boolean copyToFile(String fromFileName)
	{
		if(this.fileName == null || this.fileName.trim().length() == 0)
		{
			return false;
		}
		makePath(this.filePath);
		
		File fromFile=new File(fromFileName);
		File toFile = new File(this.fileName);
		System.out.println("To : " + this.fileName);
		try {
        int length=2097152;
        
        FileInputStream in = new FileInputStream(fromFile);
        FileOutputStream out=new FileOutputStream(toFile);
        
        FileChannel inC=in.getChannel();
        FileChannel outC=out.getChannel();
        ByteBuffer b=null;
        while(true){
            if(inC.position()==inC.size()){
                inC.close();
                outC.close();
                return true;
            }
            if((inC.size()-inC.position())<length){
                length=(int)(inC.size()-inC.position());
            }else
                length=2097152;
            b=ByteBuffer.allocateDirect(length);
            inC.read(b);
            b.flip();
            outC.write(b);
            outC.force(false);
        }
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public void createFile(String fileName, int accessMode, int createFlag) {
		this.fileName = fileName;
		this.accessMode = accessMode;
		this.createFlag = createFlag;
		
		file= new File(fileName);
		
		switch (createFlag) {
		case CREATE_NEW:
			
			break;

		case CREATE_ALWAYS:
			if(file.exists()==false)
			{
				
			}
			break;
			
		default:
			break;
		}
	}

	public void close() {

	}

	public String readLine() {
		return null;
	}

	public void write(String text) {
		try {
			  FileOutputStream fos;

			  fos = new FileOutputStream(this.fileName,false);
			  //设置为追加写的方式
			  byte[] ch=text.getBytes(this.CHAR_SET);   
			  for(int t=0;t<ch.length;t++){
			  fos.write(ch[t]);
			  }
			  fos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
	public  void replaceTxtByStr(String oldStr,String replaceStr) {
        String temp = "";
        try {
            File file = new File(this.fileName);
            FileInputStream fis = new FileInputStream(file);
            //InputStreamReader isr = new InputStreamReader(fis,System.getProperty("file.encoding"));
            //InputStreamReader isr = new InputStreamReader(fis,getUserContryCharset());
            InputStreamReader isr = new InputStreamReader(fis,this.CHAR_SET);
            BufferedReader br = new BufferedReader(isr);
            StringBuffer buf = new StringBuffer();

            // 保存该行前面的内容
            for (int j = 1; (temp = br.readLine()) != null; j++) {
                buf = buf.append(temp.replace(oldStr, replaceStr));
                buf = buf.append(System.getProperty("line.separator"));
            }


//            // 保存该行后面的内容
//            while ((temp = br.readLine()) != null) {
//                buf = buf.append(System.getProperty("line.separator"));
//                buf = buf.append(temp);
//            }

            br.close();
            FileOutputStream fos = new FileOutputStream(file);
            //PrintWriter pw = new PrintWriter(fos);
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(fos, this.CHAR_SET));  
            //new OutputStreamWriter(new FileOutputStream("yourfilepath"), "UTF-8")
            pw.write(buf.toString().toCharArray());
            pw.flush();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

	public void writeLine(String lineText) {

	}


	public static long getFileSize(String fileName) {
		File f = new File(fileName);
		return f.length();
	}

	public static boolean rename(String srcFileName, String destFileName) {
		File src = new File(srcFileName);
		File dest = new File(destFileName);
		return src.renameTo(dest);
	}

	public static boolean delete(String fileName) {
		File f = new File(fileName);
		return f.delete();
	}

	private String filePath;
	private String fileName;
	private int accessMode;
	private int createFlag;
	
	
	public static void makePath(String path){
		try {
			File pfile=new File(path);
			if(!pfile.exists()){
				boolean ok=pfile.mkdirs();
				//System.out.println(ok) ;
			}

		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public static void delFile(File file) {
		if (!file.exists()) {                      
		System.out.println("file not exist ");
		return;
		}
		boolean rs = file.delete();              
		if (rs)
		System.out.println("delete temp file success");
		else
		System.out.println("delete temp file fail");
		}
	
	public static InputStream getDownloadFile(String realPath, byte[] fileContents) throws Exception {  
	      
	    InputStream stream = null;  
	      
	    if (realPath == null && fileContents == null) {  
	        throw new Exception("not found stream Contents");  
	    }  	  
	    if (realPath != null && !"".equals(realPath)) {  
	          
	        try {  
	            File readFile = new File(realPath);  
	            FileInputStream fis = new FileInputStream(readFile);  
	              
	            byte[] buffer = new byte[(int)readFile.length()];  
	            fis.read(buffer);  
	              
	            fis.close();  
	              
	            stream = new ByteArrayInputStream(buffer);  
	        } catch (FileNotFoundException e) {  
	            throw e;  
	        }  
	    } else {  
	        stream = new ByteArrayInputStream(fileContents);  
	    }  
	      
	    return stream;  
	}  
	
	private String getUserContryCharset()
	{

		if(FileUtil.USER_COUNTRY_CHAR_SET !=null && FileUtil.USER_COUNTRY_CHAR_SET.length()> 0)
		{
			return FileUtil.USER_COUNTRY_CHAR_SET;
		}
		else
		{
			if(System.getProperty("user.country").toUpperCase().equals("JP"))
			{
				FileUtil.USER_COUNTRY_CHAR_SET="Windows-31J";
			}
		}
		
		return FileUtil.USER_COUNTRY_CHAR_SET;
	}
	
	/* 复制整个文件夹内容   
	 *    
	 * @param oldPath   
	 *            String 原文件路径 如：c:/old 
	 * @param newPath   
	 *            String 复制后路径 如：f:/new 
	 * @return boolean   
	 */    
	public static void copyFolder(String oldPath, String newPath) {     
	    
	    try {     
	        (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹     
	        File a = new File(oldPath);     
	        String[] file = a.list();     
	        File temp = null;     
	        for (int i = 0; i < file.length; i++) {     
	            if (oldPath.endsWith(File.separator)) {     
	                temp = new File(oldPath + file[i]);     
	            } else {     
	                temp = new File(oldPath + File.separator + file[i]);     
	            }     
	            if (temp.isFile()&& temp.isHidden()==false) {     
	                FileInputStream input = new FileInputStream(temp);     
	                FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());     
	                byte[] b = new byte[1024 * 5];     
	                int len;     
	                while ((len = input.read(b)) != -1) {     
	                    output.write(b, 0, len);     
	                }     
	                output.flush();     
	                output.close();     
	                input.close();     
	            }     
	            if (temp.isDirectory() && temp.isHidden()==false) {// 如果是子文件夹     
	                copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);     
	            }     
	        }     
	    } catch (Exception e) {     
	        System.out.println("复制整个文件夹内容操作出错");     
	        e.printStackTrace();     
	    }     
	}    
	
}
